﻿// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. 
// See License.txt in the project root for license information.

// This file contains workarounds to get the core parts of the Actor Framework to build as
// a portable library.  
#if PLIB_HACK
using System;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Threading.Tasks;
using System.Threading.Actors.Utilities;

namespace System
{
    // @TODO: Consider calling OutputDebugString here and in Trace.WriteLine
    internal static class Console
    {
        public static void WriteLine(String s)
        {
            if (PLibHacks.ConsoleWriteLine != null)
                PLibHacks.ConsoleWriteLine(s);
        }

        public static void WriteLine(String s, params Object[] parameters)
        {
            Console.WriteLine(String.Format(s, parameters));
        }
    }

    public static class StringExtensions
    {
        [Pure]
        public static bool Contains(this String str, char c)
        {
            Contract.Requires(str != null);

            return str.IndexOf(c) >= 0;
        }
    }

    // Portable Library does not yet contain the SerializableAttribute.  I've asked the CLR Portable Library 
    // experts to look at adding it in a future version, but it may require a new release of Windows Phone.
    // In the mean time, by defining our own System.SerializableAttribute, we can fake out the C# compiler. 
    // As you know, the SerializableAttribute is a pseudo-custom attribute meaning it simply sets a bit in 
    // metadata from 0 to 1.  So this will not show up as a curiously-odd attribute on types.  
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Delegate, Inherited = false)]
    internal class SerializableAttribute : Attribute
    {
    }
}

namespace System.Diagnostics
{
    internal static class Trace
    {
        public static void WriteLine(String s) 
        {
            if (PLibHacks.TraceWriteLine != null)
                PLibHacks.TraceWriteLine(s);
            else
                Console.WriteLine(s);
        }

        public static void WriteLine(String s, params Object[] parameters)
        {
            String finalString = String.Format(s, parameters);
            Trace.WriteLine(finalString);
        }
    }
}

namespace System.Threading.Actors.Utilities
{
    // Light-up, essentially.
    public static class PLibHacks
    {
        public static Action<String> ConsoleWriteLine { get; set; }
        public static Action<String> TraceWriteLine { get; set; }
    }
}
#endif  // PLIB_HACK
